//
//  PMViewController.m
//  consumer2
//
//  Created by Philip Mulcahy on 11/01/2012.
//  Copyright (c) 2012 Philip Mulcahy. All rights reserved.
//

#import "PMViewController.h"
#import "note-recog/IConsumer.h"
#import "note-recog/INoteEvent.h"
#import <iostream>

using namespace std;

@implementation PMViewController

@synthesize label=_label;
@synthesize userName=_userName;

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    recog = 0;
	// Do any additional setup after loading the view, typically from a nib.
}

- (void)viewDidUnload
{
    [self setLabel:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
	[super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
	[super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

class Wrapper : public IConsumer
{
private:
    PMViewController * const _wrapped;
    
public:
    Wrapper( PMViewController * wrapped ) : _wrapped(wrapped){}
    
    virtual void onNoteRecognized(const INoteEvent& evt)
    {
        @autoreleasepool
        {
            const string noteString = evt.toString();
            const char* cstring = noteString.c_str();
            NSString __strong * nsstring = [NSString stringWithUTF8String:cstring];
            
            [_wrapped.label performSelectorOnMainThread:@selector(setText:) 
                            withObject:nsstring 
                            waitUntilDone:YES];
            
            //cout << "onNoteRecognized(" << evt << ")" << endl;
        }
    }
};

- (IBAction)startIt:(id)sender {
    if( recog )
    {
        cout << "already started" << endl;
        return;
    }
    else {
        cout << "starting" << endl;
    }
    
    cout << "PMViewController.startIt() created Recog" << endl;
    recog = new Recog(new Wrapper(self));
    cout << "PMViewController.startIt() created Recog" << endl;
    
    recog->start(); 
}

- (IBAction)stopIt:(id)sender {
    if( !recog ) {
        cout << "already stopped" << endl;
    }
    delete recog;
    recog = 0;
    self.label.text = @"stopped";
}

@end
